<template>
  <div style="margin-top: 0;"> <!-- 将这里的margin-top设为0，减少顶部间距 -->
    <div class="toolbar" style="margin-left: 0;"> <!-- 去除左侧间距 -->
      <el-button type="primary" @click="openAddDialog">新增企业</el-button>
    </div>
    <el-table :data="currentPageData" style="width: 100%; margin-left: 0;" border :row-class-name="tableRowClassName"> <!-- 去除表格左侧间距 -->
      <el-table-column prop="entId" label="企业ID" width="100" align="center"></el-table-column>
      <el-table-column prop="entName" label="企业名称" width="120" align="center"></el-table-column>
      <el-table-column prop="entAddr" label="企业地址" width="120" align="center"></el-table-column>
      <el-table-column prop="entPhone" label="企业电话" width="120" align="center"></el-table-column>
      <el-table-column prop="entPartner" label="是否为合作企业" width="129" align="center"></el-table-column>
      <el-table-column prop="entContact" label="联系人" width="100" align="center"></el-table-column>
      <el-table-column prop="entContactPhone" label="联系人电话" width="120" align="center"></el-table-column>
      <el-table-column prop="created" label="申请有效时间" width="200" :formatter="formatDate" align="center"></el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #default="{ row }">
          <el-button type="danger" @click="deleteEnterprise(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin: 0 0 20px 0; " @current-change="handleCurrentChange" :current-page="currentPage"
      :page-size="pageSize" :total="totalRecords" layout="total, prev, pager, next, jumper" />

    <el-dialog v-model="dialogVisible" title="新增企业信息" width="60%">
      <el-form :model="newEnterprise" label-width="120px">
        <el-form-item label="企业名称" prop="entName">
          <el-input v-model="newEnterprise.entName" />
        </el-form-item>
        <el-form-item label="企业地址" prop="entAddr">
          <el-input v-model="newEnterprise.entAddr" />
        </el-form-item>
        <el-form-item label="企业电话" prop="entPhone">
          <el-input v-model="newEnterprise.entPhone" />
        </el-form-item>
        <el-form-item label="是否为合作企业" prop="entPartner">
          <el-select v-model="newEnterprise.entPartner" placeholder="请选择">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="entContact">
          <el-input v-model="newEnterprise.entContact" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="entContactPhone">
          <el-input v-model="newEnterprise.entContactPhone" />
        </el-form-item>
        <el-form-item label="申请有效时间" prop="validTime">
          <el-date-picker v-model="newEnterprise.validTime" type="datetime" placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" @change="handleDateChange" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addEnterprise"> 新增 </el-button>
        </span>
      </template>
    </el-dialog>
    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>

<script>
// 这里代码保持不变，不修改功能相关逻辑
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/json';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { enterpriseListPageApi, enterpriseAddApi, enterpriseDeleteApi } from '@/api/ent-api';

export default {
  components: {
    Plus
  },
  setup() {
    // 新增企业对话框可见性
    const dialogVisible = ref(false);
    // 当前页码
    const currentPage = ref(1);
    // 每页数量
    const pageSize = ref(10);
    // 总记录数
    const totalRecords = ref(0);
    // 所有企业数据
    const allEnterprises = ref([]);
    // 加载状态
    const isLoading = ref(false);
    // 新增企业表单数据
    const newEnterprise = reactive({
      entName: '',
      entAddr: '',
      entPhone: '',
      entPartner: '',
      entContact: '',
      entContactPhone: '',
      validTime: null
    });

    // 当前页数据计算属性
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return allEnterprises.value.slice(start, end);
    });

    // 获取企业列表
    const fetchAllEnterprises = async () => {
      isLoading.value = true;
      try {
        // 打印请求参数
        console.log('请求参数:', {
          page: currentPage.value,
          size: pageSize.value
        });
        const { records, total } = await enterpriseListPageApi({
          page: currentPage.value,
          size: pageSize.value
        });
        // 打印响应数据
        console.log('响应数据:', { records, total });
        if (Array.isArray(records)) {
          const newData = records.map(item => ({
            ...item,
            entPartner: item.entPartner ? '是' : '否'
          }));
          const startIndex = (currentPage.value - 1) * pageSize.value;
          const endIndex = startIndex + newData.length;
          allEnterprises.value.splice(startIndex, newData.length, ...newData);
          totalRecords.value = total || 0;
        } else {
          ElMessage.error('接口返回的数据格式不正确，请联系管理员');
        }
      } catch (error) {
        ElMessage.error('获取企业列表失败，请稍后再试');
      } finally {
        isLoading.value = false;
      }
    };

    onMounted(async () => {
      await fetchAllEnterprises();
    });

    // 打开新增企业对话框
    const openAddDialog = () => {
      dialogVisible.value = true;
      Object.assign(newEnterprise, {
        entName: '',
        entAddr: '',
        entPhone: '',
        entPartner: '',
        entContact: '',
        entContactPhone: '',
        validTime: null
      });
    };

    // 新增企业
    const addEnterprise = async () => {
      const requiredFields = [
        'entName',
        'entAddr',
        'entPhone',
        'entPartner',
        'entContact',
        'entContactPhone',
        'validTime'
      ];
      const missingFields = requiredFields.filter(field => !newEnterprise[field]);
      if (missingFields.length > 0) {
        ElMessage.error('请填写所有必填项');
        return;
      }

      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(newEnterprise.entPhone)) {
        ElMessage.error('请输入有效的企业电话号码');
        return;
      }
      if (!phoneRegex.test(newEnterprise.entContactPhone)) {
        ElMessage.error('请输入有效的联系人电话号码');
        return;
      }

      const existingEnterprises = allEnterprises.value;
      const isEntNameDuplicated = existingEnterprises.some(
        enterprise => enterprise.entName === newEnterprise.entName
      );
      if (isEntNameDuplicated) {
        ElMessage.error('企业名称已存在，请重新输入');
        return;
      }

      newEnterprise.entPartner = newEnterprise.entPartner === '1';
      try {
        const response = await enterpriseAddApi(newEnterprise);
        await fetchAllEnterprises();
        totalRecords.value = allEnterprises.value.length;
        dialogVisible.value = false;
        ElMessage.success('新增企业成功');
      } catch (error) {
        ElMessage.error('新增企业失败，请稍后再试');
      }
    };

    // 删除企业
    const deleteEnterprise = async (row) => {
      const isConfirmed = confirm('确定要删除该企业吗？');
      if (isConfirmed) {
        isLoading.value = true;
        try {
          const response = await enterpriseDeleteApi(row.entId);
          const isSuccess = Boolean(response?.data);
          if (isSuccess) {
            await fetchAllEnterprises();
            totalRecords.value = allEnterprises.value.length;
            ElMessage.success('企业删除成功');
          } else {
            const errorMessage = response && response.msg ? response.msg : '企业删除失败';
            ElMessage.error(errorMessage);
          }
        } catch (error) {
          console.error('删除企业时出错:', error);
          ElMessage.error('企业删除失败，请稍后再试');
        } finally {
          isLoading.value = false;
        }
      }
    };

    // 分页切换时重新获取企业列表
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchAllEnterprises();
    };

    const handleDateChange = (value) => {
      newEnterprise.validTime = value;
    };
    const tableRowClassName = (row, rowIndex) => {
      return {
        'success-row': row.rowIndex%2 === 0
      };
    };

    const formatDate = (row, column, cellValue) => {
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    };


    return {
      dialogVisible,
      newEnterprise,
      allEnterprises,
      currentPageData,
      currentPage,
      pageSize,
      totalRecords,
      isLoading,
      openAddDialog,
      addEnterprise,
      deleteEnterprise,
      handleCurrentChange,
      handleDateChange,
      formatDate,
      tableRowClassName
    };
  }
};

</script>

<style>
.toolbar {
  margin-bottom: 10px;
}

.loading {
  text-align: center;
  margin-top: 10px;
  color: #999;
}
  
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>